package routers

import (
	"api/models"
	"api/src/basic"

	b "github.com/beego/beego/v2/server/web"
	"github.com/beego/beego/v2/server/web/filter/cors"
)

type Res struct {
	Id     uint32
	Method string
	Path   string
	Name   string
	Params string
	Func   interface{}
}

func InitRouter() []models.Resource {
	// 重要约定：get 查询、删除，post 新增、编辑

	// 基本路由
	// id命名约定：
	// 100：百位 栏目，十位 页面，个位 具体接口
	data := []Res{
		{Id: 100, Path: "user/login", Name: "后台管理员登录", Params: "username=admin,password=16位md5加密", Func: basic.UserC.Login},
		{Id: 101, Path: "user/changePassword", Name: "修改登录密码", Params: "oldPassword=12345,newPassword=67890", Func: basic.UserC.ChangePassword},

		{Id: 110, Path: "basic/resource", Name: "获取资源数据", Func: basic.ResourceC.Search},

		{Id: 120, Path: "basic/logger", Name: "获取日志数据", Func: basic.LoggerC.Search},
		{Id: 121, Path: "basic/logger/forbidIP", Name: "封IP", Func: basic.LoggerC.ForbidIP, Params: "ip=192.168.128.100,day=1"},
		{Id: 122, Path: "basic/logger/forbidUser", Name: "封用户", Func: basic.LoggerC.ForbidUser, Params: "userId=1,day=1"},
		{Id: 123, Path: "basic/logger/getUser", Name: "获取单条用户数据", Func: basic.LoggerC.GetUser, Params: "id=1"},

		{Id: 130, Path: "basic/role", Name: "获取角色数据", Func: basic.RoleC.Search},
		{Id: 131, Path: "basic/role/add", Method: "post", Name: "新增角色数据", Func: basic.RoleC.Add},
		{Id: 132, Path: "basic/role/edit", Method: "post", Name: "编辑角色数据", Func: basic.RoleC.Edit},
		{Id: 133, Path: "basic/role/remove", Name: "删除角色数据", Func: basic.RoleC.Remove},

		{Id: 140, Path: "basic/user", Name: "获取用户数据", Func: basic.UserC.Search},
		{Id: 141, Path: "basic/user/add", Method: "post", Name: "新增用户数据", Func: basic.UserC.Add},
		{Id: 142, Path: "basic/user/edit", Method: "post", Name: "编辑用户数据", Func: basic.UserC.Edit},
		{Id: 143, Path: "basic/user/remove", Name: "删除用户数据", Func: basic.UserC.Remove},
		{Id: 144, Path: "basic/user/roleSelectData", Name: "角色列表框数据", Func: basic.UserC.RoleSelectData},
	}

	// 业务路由
	data = append(data, bottle_res()...)

	mapping := map[string]func(path string, f interface{}){
		"get":  b.CtrlGet,
		"post": b.CtrlPost,
	}
	resData := []models.Resource{}
	for _, i := range data {
		if i.Method == "" {
			i.Method = "get"
		}
		mapping[i.Method]("api/"+i.Path, i.Func) // 挂载路由
		resData = append(resData, models.Resource{i.Id, i.Method, i.Path, i.Name, i.Params})
	}

	// 允许客户端跨域访问
	// 参考自：beego 解决跨域问题
	// https://baijiahao.baidu.com/s?id=1676511542165937570
	b.InsertFilter("*", b.BeforeRouter, cors.Allow(&cors.Options{
		AllowAllOrigins:  true,
		AllowCredentials: true,
		AllowHeaders:     []string{"Content-Type", "k"},
		AllowMethods:     []string{"*"},
		ExposeHeaders:    []string{"*"},
	}))

	//logs.Info("路由已准备好。")
	return resData
}
